package com.example.p833email;

import com.icegreen.greenmail.util.GreenMail;
import com.icegreen.greenmail.util.ServerSetup;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import java.util.Properties;

@SpringBootApplication
public class P833EmailApplication {

	public static void main(String[] args) {
		SpringApplication.run(P833EmailApplication.class, args);
	}

	@Bean
	public ApplicationRunner startupMailSender(JavaMailSender mailSender) {



		return (args) -> {
			GreenMail greenMail = new GreenMail(new ServerSetup[]{
					ServerSetup.SMTP,
					ServerSetup.POP3,
					ServerSetup.IMAP
			});
			greenMail.start();

			mailSender.send((msg) -> {
				MimeMessageHelper helper = new MimeMessageHelper(msg);
				helper.setTo("recipient@some.where");
				helper.setFrom("spring-boot-2-recipes@apress.com");
				helper.setSubject("Status message");
				helper.setText("All is well.");
			});

			//收邮件
			Session session = Session.getInstance(new Properties());
			Store store = session.getStore("pop3");
			store.connect("localhost", greenMail.getPop3().getPort(), null, null);

			Folder inbox = store.getFolder("INBOX");
			inbox.open(Folder.READ_ONLY);

			Message[] messages = inbox.getMessages();
			for(Message message : messages) {
				System.out.println(message.getSubject());
				System.out.println(message.getContent());
			}

			inbox.close();
			store.close();
		};
	}
}